<script setup>
import { DXF_LAYERS } from '@/components/roomConstant/common.js';
import { Input, InputNumber, message, RadioGroup, Select } from 'ant-design-vue';

const fatherData = inject('fatherData');
const roomInfoVisible = ref(false);
const isUpdate = ref();
const emits = defineEmits(['updateRoom']);

const form = reactive({
  id: '',
  name: '',
  area: 0,
  isRoomArea: '',
  roomUseType: '',
  roomUseUnit: '',
});
const roomColumn = {
  data: [
    {
      label: '房间号/名称',
      dataIndex: 'name',
      value: '',
      component: markRaw(Input),
    },
    {
      label: '面积(㎡)',
      dataIndex: 'area',
      value: '',
      component: markRaw(InputNumber),
      props: {
        min: 0,
        precision: 2,
      }
    },
    // {
    //   label: '是否房间',
    //   dataIndex: 'isRoomArea',
    //   value: '',
    //   component: markRaw(RadioGroup),
    //   props: {
    //     options: [
    //       { label: '是', value: true },
    //       { label: '否', value: false }
    //     ],
    //     onChange: (value) => {
    //       if (value.target.value) {
    //         roomInfoData.value.push(...roomColumn.roomUseData);
    //       } else {
    //         roomInfoData.value.splice(-2);
    //       }
    //     }
    //   }
    // },
  ],
  roomUseData: [
    // {
    //   label: '房屋用途',
    //   dataIndex: 'roomUseType',
    //   value: '',
    //   component: markRaw(Select),
    //   props: {
    //     options: fatherData.specialRoomOptions.roomUseType,
    //   },
    // },
    // {
    //   label: '使用单位',
    //   dataIndex: 'roomUseUnit',
    //   value: '',
    //   component: markRaw(Select),
    //   props: {
    //     options: fatherData.specialRoomOptions.roomUseUnit,
    //   },
    // }
  ]
};
const roomInfoData = ref([]);
const sourceData = ref();

const formRef = ref();
// 添加校验规则
const rules = {
  name: [{ required: true, message: '请输入房间号/名称' }],
  area: [{ required: true, message: '请输入面积' }],
  isRoomArea: [{ required: true, message: '请选择是否房间' }],
  roomUseType: [{ required: true, message: '请选择房屋用途' }],
  roomUseUnit: [{ required: true, message: '请选择使用单位' }]
};

const tagColors = ['green', 'cyan', 'blue', 'purple', 'pink', 'orange', 'red'];


const resetForm = () => {
  for (let key in form) {
    switch (key) {
      case 'area':
      default:
        form[key] = '';
    }
  }
};

// 处理面，生成预览信息
const featuresHandle = (currentFeature) => {
  resetForm();
  if (!currentFeature || !fatherData.currentRowData) return;
  const currentId = currentFeature.properties.id;
  let name = currentFeature.properties.name, area = currentFeature.properties.area;
  const { roomUseType, roomUseUnit } = fatherData.specialRoomOptions;
  sourceData.value = {
    id: currentId,
    name,
    area,
    isRoomArea: currentFeature.properties.layer === DXF_LAYERS.TX,
    roomUseType: roomUseType.find(item => item.value === currentFeature.properties.roomUseType)?.value,
    roomUseUnit: roomUseUnit.find(item => item.value === currentFeature.properties.roomUseUnit)?.value,
  };
  Object.assign(form, sourceData.value);
  setRoomInfo();
};

const setRoomInfo = () => {
  roomInfoData.value = form.isRoomArea ?
      [...roomColumn.data, ...roomColumn.roomUseData] :
      roomInfoData.value = [...roomColumn.data];

  const { roomUseType, roomUseUnit } = fatherData.specialRoomOptions;
  roomInfoData.value.forEach(item => {
    switch (item.dataIndex) {
      case 'isRoomArea':
        item.value = form.isRoomArea ? '是' : '否';
        break;
      case 'roomUseType':
        item.value = roomUseType.find(it => it.value === form[item.dataIndex])?.label;
        break;
      case 'roomUseUnit':
        item.value = roomUseUnit.find(it => it.value === form[item.dataIndex])?.label;
        break;
      default:
        item.value = form[item.dataIndex];
        break;
    }
  });
};

// 编辑房间信息
const updateRoomInfo = () => {
  isUpdate.value = true;
};

// 取消
const handleCancel = () => {
  isUpdate.value = false;
  Object.assign(form, sourceData.value);
  if (form.isRoomArea) {
    roomInfoData.value = [...roomColumn.data, ...roomColumn.roomUseData];
  } else {
    roomInfoData.value = [...roomColumn.data];
  }
  if (fatherData.roomInfoFeature.isDraw) roomInfoVisible.value = false;
};

// 保存
const handleOk = async () => {
  // 强制格式化面积为两位小数
  if (form.area !== '' && form.area !== undefined) {
    form.area = parseFloat(form.area || 0).toFixed(2);
  }
  try {
    await formRef.value.validateFields();
    setRoomInfo();
    isUpdate.value = false;
    roomInfoVisible.value = false;
    emits('updateRoom', { isDraw: fatherData.roomInfoFeature.isDraw, form });
  } catch (error) {
    console.log('校验失败:', error);
  }
};

// 点击面
watch(() => fatherData.roomInfoFeature.feature, (newVal) => {
  // console.log('房间属性弹窗==== ', newVal);
  if (newVal) {
    isUpdate.value = fatherData.roomInfoFeature.isDraw || false;
    roomInfoVisible.value = true;
    featuresHandle(newVal);
  }
});
</script>

<template>
  <a-modal
      v-model:open="roomInfoVisible"
      :title="isUpdate ? '编辑房间':'预览房间'"
      centered
      :width="700"
      @cancel="handleCancel"
  >
    <template #footer>
      <div class="footer-btn">
        <div v-show="!isUpdate" class="update-btn">
          <a-button type="primary" :style="{background:'orange'}" @click="updateRoomInfo">编辑</a-button>
        </div>
        <div v-show="isUpdate" class="ok-btn">
          <a-button type="dashed" @click="handleCancel">取消</a-button>
          <a-button type="primary" @click="handleOk">确认</a-button>
        </div>
      </div>
    </template>
    <a-form ref="formRef" :model="form" :rules="rules">
      <div class="room-info-content">
        <div class="preview" v-if="!isUpdate">
          <a-descriptions :column="2" bordered>
            <a-descriptions-item v-for="(item,index) in roomInfoData" :label="item.label" :key="item.dataIndex">
              <a-tag :color="tagColors[index % tagColors.length]">{{ item.value }}</a-tag>
            </a-descriptions-item>
          </a-descriptions>
        </div>
        <div class="preview" v-else>
          <a-descriptions :column="2" bordered>
            <a-descriptions-item v-for="item in roomInfoData" :label="item.label" :key="item.dataIndex">
              <a-form-item :name="item.dataIndex">
                <component
                    v-model:value="form[item.dataIndex]"
                    :is="item.component"
                    v-bind="item.props" style="width: 120px">
                </component>
              </a-form-item>
            </a-descriptions-item>
          </a-descriptions>
        </div>
      </div>
    </a-form>
  </a-modal>
</template>

<style scoped lang="scss">
.footer-btn {

  .update-btn {
    text-align: left;
  }

  .ok-btn {
    text-align: right;
  }

  .ant-btn {

    &:hover {
      filter: opacity(0.8);
    }
  }
}

.preview {
  .ant-form-item {
    margin-bottom: 0;
  }
}
</style>
